package com.example.baselibrary.commonutil;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

public class PermissionUtil {

    private static final String PERMISSION_DENIED_MESSAGE_PRE = "您已拒绝了";
    private static final String PERMISSION_DENIED_MESSAGE_SUFF = "权限,无法使用此功能!";

    public static boolean checkPermission(Activity activity, int requestCode, String permission,
                                          boolean autoRequest) {
        if (ActivityCompat.checkSelfPermission(activity, permission) == PackageManager
                .PERMISSION_GRANTED) {
            return true;
        }
        if (autoRequest) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                new QMUIDialog.MessageDialogBuilder(activity)
                        .setMessage(PERMISSION_DENIED_MESSAGE_PRE
                            + getPermissionChinese(permission) + PERMISSION_DENIED_MESSAGE_SUFF)
                        .show();
            } else {
                ActivityCompat.requestPermissions(activity, new String[] {permission}, requestCode);
            }
        }
        return false;
    }

    private static String getPermissionChinese(String permission) {
        switch (permission) {
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
            case Manifest.permission.READ_EXTERNAL_STORAGE:
                return "文件读写";
            case Manifest.permission.CAMERA:
                return "相机";
            case Manifest.permission.ACCESS_FINE_LOCATION:
                return "GPS";
        }
        return permission;
    }
}
